//
//  AppDelegate.swift
//  swift-GWYWeiBo
//
//  Created by x on 2017/3/9.
//  Copyright © 2017年 HLB. All rights reserved.
//

import UIKit

let GWYSwitchRootController = "GWYSwitchRootController"


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        //注册一个通知
        NotificationCenter.default.addObserver(self, selector: #selector(switchRootController(notiy:)), name: NSNotification.Name(rawValue: GWYSwitchRootController), object: nil)
        //为UITabBar 和navitionBar设置外观 外观一旦设置全局有效,所以应该在程序一进来就设置
        UINavigationBar.appearance().tintColor = UIColor.orange
        UITabBar.appearance().tintColor = UIColor.orange
        //1.创建一个window
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.backgroundColor = UIColor.white
        //2.创建一个根控制器
        window?.rootViewController = defaultController()
        window?.makeKeyAndVisible()
        return true
    }
    
    /// 监听更改根控制器的通知方法
    func switchRootController(notiy: NSNotification) -> Void {
        if notiy.object as! Bool {
            //更换更控制器为主控制器
            window?.rootViewController = MainViewController()
        }else {
            window?.rootViewController = WelcomeViewController()
        }
    }
    /// 判断显示那个控制器
    ///
    /// - Returns: 返回当前应该显示的控制器
    private func defaultController() -> UIViewController {
        //判断用户是否登入
        if UserAccess.userLonginState() {
            //检查版本有没有更新
            return isNewVersion() ? NewFeatureCollectionViewController() : WelcomeViewController()
        }else {
            return MainViewController()
        }
    }
    /// 判断是否是新版本
    private func isNewVersion() -> Bool {
        //1.拿到新版本号 和旧版本号
        let currentVersion = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
        let sandboxVersion = UserDefaults.standard.object(forKey: "CFBundleShortVersionString") as? String ?? "0.0"
        //3.把最新的版本号储存起来
        UserDefaults.standard.set(currentVersion, forKey: "CFBundleShortVersionString")
        //2.比较两个版本号之间的大小  默认是降序就是 新版本
        if currentVersion.compare(sandboxVersion) == ComparisonResult.orderedDescending {
            return true
        }
        //如果新版本大于旧版本 则说明是新版本 反之是旧版本
        return false
    }
}

